import L from 'leaflet';
import 'static/js/L.Control.MousePosition.js'
// 小地图
import 'static/js/Control.MiniMap.js'
// 比例尺
import 'static/js/leaflet.nauticscale.min.js'
// 全屏控制
import 'static/js/Control.FullScreen.js'
// 打印地图
import 'static/js/leaflet.browser.print.js'
import 'static/js/leaflet.browser.print.utils.js'
import 'static/js/leaflet.browser.print.sizes.js'

// 地图平移
import 'static/js/L.Control.Pan.js'
// 地图缩放级别
import 'static/js/L.Control.Zoominfo.js'
// 量尺
import 'static/js/leaflet-ruler.js'
// 面积测量
import 'static/js/leaflet-measure.js'

//船高亮
import 'static/js/leaflet.marker.highlight.js'

import 'static/js/leaflet.polylineDecorator.js'

//绘制所需要的文件
import 'static/js/draw-lib/Leaflet.draw.js'
import 'static/js/draw-lib/Toolbar.js'
import 'static/js/draw-lib/Tooltip.js'

import 'static/js/draw-lib/ext/TouchEvents.js'
import 'static/js/draw-lib/ext/GeometryUtil.js'
import 'static/js/draw-lib/ext/LatLngUtil.js'
import 'static/js/draw-lib/ext/LineUtil.Intersect.js'
import 'static/js/draw-lib/ext/Polyline.Intersect.js'
import 'static/js/draw-lib/ext/Polygon.Intersect.js'

import 'static/js/draw-lib/draw/DrawToolbar.js'
import 'static/js/draw-lib/draw/handler/Draw.Feature.js'
import 'static/js/draw-lib/draw/handler/Draw.SimpleShape.js'
import 'static/js/draw-lib/draw/handler/Draw.Circle.js'
import 'static/js/draw-lib/draw/handler/Draw.Marker.js'
import 'static/js/draw-lib/draw/handler/Draw.Polyline.js'
import 'static/js/draw-lib/draw/handler/Draw.Polygon.js'
import 'static/js/draw-lib/draw/handler/Draw.Rectangle.js'

import 'static/js/draw-lib/edit/EditToolbar.js'
import 'static/js/draw-lib/edit/handler/EditToolbar.Edit.js'
import 'static/js/draw-lib/edit/handler/EditToolbar.Delete.js'
import 'static/js/draw-lib/edit/handler/Edit.Poly.js'
import 'static/js/draw-lib/edit/handler/Edit.SimpleShape.js'
import 'static/js/draw-lib/edit/handler/Edit.Circle.js'
import 'static/js/draw-lib/edit/handler/Edit.Marker.js'
import 'static/js/draw-lib/edit/handler/Edit.Rectangle.js'

import 'static/js/draw-lib/Control.Draw.js'

//绘制控件
import 'static/js/leaflet-control-draw.js'

//业务图层控件
import 'static/js/leaflet-control-buslayer.js'

//清除控件
import 'static/js/leaflet-control-clear.js'

// 海图3中模式切换
import 'static/js/leaflet.groupedlayercontrol.js'
import 'static/js/basemaps.js'

//业务server
import * as mabardCoordService from '@/services/MabardCoordService'
import sosOrgService from '@/services/SosOrgService'
import sosFlyDeviceService from '@/services/SosFlyDeviceService'
import emWarehouseService from '@/services/EmWarehouseService'
import cctvSiteService from '@/services/CctvSiteService'
import vtsSubCenterService from '@/services/VtsSubCenterService'
import vtsRadarStService from '@/services/VtsRadarStService'
import lawPeopleService from '@/services/LawPeopleService'
import emmerShipService from '@/services/EmmerShipService'
import sosShipProService from '@/services/SosShipProService.js'
import sosShipSocService from '@/services/SosShipSocService.js'
import * as shipService from '@/services/ShipService'
import index from "../../../router";

var parentobj;
var mapobj;
var mapGrouplayerCctvSite = []; //执法装备-cctv系统
var mapGrouplayerVtsSubCenter = []; //执法装备-vts分中心
var mapGrouplayerVtsRadarSt = []; //执法装备-vts雷达站
var mapGrouplayerSosOrganization = []; //搜救机构
var mapGrouplayerSosFlyDevice = []; //搜救力量-飞行器
var mapGrouplayerEmWarehouse = []; //溢油力量-溢油应急库
var mapGrouplayerSysUser = []; //执法人员
var mapGrouplayerEmmerShip = []; //溢油船舶
var mapGrouplayerSosShipPro = []; //专业搜救船舶
var mapGrouplayerSosShipSoc = []; //社会力量搜救船舶
var mapGrouplayerZfct = []; //执法船艇


export async function createMap(homeObj) {
  parentobj = this;
  // 全屏控制
  this.map = new L.Map('mapbzxmap', {
    fullscreenControl: true,
    fullscreenControlOptions: {
      position: 'topright'
    },
    zoominfoControl: true,
    zoomControl: false,
    attributionControl: true,
    layers: [MapData.Basemaps.all]
  })
  mapobj = this.map;
  initMap();

  this.map.on("moveend", (e) => {
  });
  this.map.on("zoomend", (e) => {
  });
  this.map.on("movestart", (e) => {
  });
  this.map.on("zoomstart", (e) => {
  });
  this.map.on("move", (e) => {
  });
  this.map.on("zoom", (e) => {
  });
  this.map.on("mousemove", (e) => {
  })
  this.map.on('click', (e) => {
  })
/*
  this.map.on('onShowHideBusLayer', (e) => {
    ShowHideBusLayer(e);
  })
*/
  showOrganiza(); //显示海事机构，例如 长岛海事处
}

//初始化地图
function initMap() {
  parentobj.osm = new L.TileLayer(parentobj.$config.OSM_URL, parentobj.$config.OSM_OPTION)
  mapobj.addLayer(parentobj.osm)

  mapobj.setView(new L.LatLng(37.5, 120.7), 9);

/*
  var options = {
    position: 'topright',
    lengthUnit: {
      factor: 0.539956803, //  from km to nm
      display: 'nm',
      decimal: 2
    }
  };
  //业务图层显示和隐藏
  L.control.buslayer(options).addTo(mapobj);
*/
}

export function redrawMap(homeObj, homeObj1) {
}

export function updateMap(homeObj, homeObj1) {
}

const makeIcon = img => {
  return L.icon({iconUrl: img, iconSize: [28, 22], iconAnchor: [13,10]})
}

//显示业务对象地图点位
//type CctvSite 执法装备-cctv系统，VtsSubCenter 执法装备-VTS分中心  VtsRadarSt 执法装备-VTS雷达站
// //SosOrg 搜救机构，SosFlyDevice 搜救力量-飞行器，EmWarehouse 溢油力量-溢油应急库
const BUSTYPE_CCTV = 'CctvSite'
const BUSTYPE_VTS_CENTER = 'VtsSubCenter'
const BUSTYPE_VTS_RADAR = 'VtsRadarSt'
const BUSTYPE_SOS_ORG = 'SosOrganization'
const BUSTYPE_SOS_FLYDEV = 'SosFlyDevice'
const BYSTYPE_EM_WAREHOUSE = 'EmWarehouse'
const BYSTYPE_SYS_USER = 'SysUser'
const BYSTYPE_EMMERSHIP = 'EmmerShip'
const BYSTYPE_SOSSHIPPRO = 'SosShipPro'
const BYSTYPE_SOSSHIPSOC = 'SosShipSoc'
const BYSTYPE_ZFCT = 'Zfct'

const ICON_CCTV_SITE = makeIcon('/static/css/images/mapobj/CctvSite.png')
const ICON_VTS_SUB_CENTER = makeIcon('/static/css/images/mapobj/VtsSubCenter.png')
const ICON_VTS_RADAR_ST = makeIcon('/static/css/images/mapobj/VtsRadarSt.png')
const ICON_SOS_ORG = makeIcon('/static/css/images/mapobj/SosOrg.png')
const ICON_SOS_FLY_DEV = makeIcon('/static/css/images/mapobj/SosFlyDevice.png')
const ICON_EM_WAREHOUSE = makeIcon('/static/css/images/mapobj/EmWarehouse.png')
const ICON_SYS_USER = makeIcon('/static/css/images/mapobj/people.png')
const ICON_EMMERSHIP = makeIcon('/static/css/images/mapobj/emship.png')
const ICON_SOSSHIPPRO = makeIcon('/static/css/images/mapobj/zy_sos_hip.png')
const ICON_SOSSHIPSOC = makeIcon('/static/css/images/mapobj/shlljz_ship.png')
const ICON_ZFCT = makeIcon('/static/css/images/mapobj/zfct.png')

//获取海事处
function getOrganiza() {
  return mabardCoordService.getAll();
}
//海图上显示各个海事处标签，蓝色海事处名称标签
function showOrganiza() {
  parentobj.tooltip=[];
  getOrganiza().then((mabs) => {
    let idary=[];
    for (let i = 0; i < mabs.length; i++) {
      let dividvalue="divIconOrg"+i.toString();

      let markeroption={};
      markeroption.className='';
      let mab = mabs[i];
      if (mab.organiza.orgCode === '160000') {
        markeroption.html='<div id="'+dividvalue+'" class="my-label">'+mab.organiza.name+'</div>';
        let myIcon = L.divIcon(markeroption);
        let markertemp=L.marker([37.7, 121.4], {icon: myIcon});
        parentobj.tooltip.push(markertemp)
        markertemp.addTo(mapobj);
      } else {
        markeroption.html='<div id="'+dividvalue+'" class="my-label">'+mab.organiza.name+'</div>';
        let myIcon = L.divIcon(markeroption);
        let markertemp=L.marker([mab.latitude,mab.longitude], {icon: myIcon});
        parentobj.tooltip.push(markertemp)
        markertemp.addTo(mapobj);
      }
      idary.push(dividvalue);
    }
    for (let k=0;k<idary.length;k++){
      let divmatker=document.getElementById(idary[k]).parentNode;
      divmatker.style.zIndex =10;
    }
  })
}
function convertName(o) {
  if (o.name == null || o.name == "") {
    o.name = o.cnName;
  }
  if (o.name == null || o.name == "") {
    o.name = o.companyName;
  }
  if (o.name == null || o.name == "") {
    o.name = o.fullname;
  }
  if (o.name == null || o.name == "") {
    o.name = o.shipName;
  }
  return o;
}
function getMmsiQuery(ary) {
  if (ary.length > 0) {
    let ret = "";
    for (let k = 0; k < ary.length; k++) {
      if (ary[k].mmsi != null && ary[k].mmsi.trim().length > 0) {
        if (ret == "") {
          ret = "terminalCode.in=" + ary[k].mmsi;
        } else {
          ret = ret + "," + ary[k].mmsi;
        }
      }
    }
    return ret;
  } else {
    return "";
  }
}
function showMapObj(dataary,mapobj,icon,objArray) {
  for (let n = 0; n < dataary.length; n++) {
    let o = convertName(dataary[n]);
    let mk = createMapObjIcon(o, icon);
    if (mk) {
      mapobj.addLayer(mk);
      objArray.push(mk);
    }
  }
}
function createMapObjIcon(targetobj, icon, tipInfoOfficeX = 10, tipInfoOfficeY = 15) {
  if (!targetobj.latitude && !targetobj.longitude) {
    return null
  }

  let latlng = L.latLng(targetobj.latitude, targetobj.longitude);
  let lmarkerOption = {
    draggable: false,//是否可以拖动
    rotationAngle: 0, //方向，正北是0，顺时针，共360
    icon,
    data: targetobj	 //为了在点击时能获取到相关的信息
  };
  let mker = L.marker(latlng, lmarkerOption);

  var tiptitle = targetobj.name;
  var tipOptin = {
    offset: [tipInfoOfficeX, tipInfoOfficeY], //偏移量，第一个参数是X方向，第二个参数是Y方向，当direction是left或者right时，只有第一个参数起作用，当direction是top或者bottom时，只有第二个参数起作用
    direction: "right",//提示信息显示位置，有 left right top bottom auto
    permanent: false,
    opacity: 0.8,//透明度
    className: "realtarget-label-target" //css文件中定义的样式名称，例如：.realtarget-label-target{background-color:transparent;background:transparent;background:rgba(255,255,255,0.3);background-clip:padding-box;border-color:#000000;border-radius:2px;border-style:solid;border-width:1;color:#000000;display:block;font:12px/1.5 "Helvetica Neue",Arial,Helvetica,sans-serif;font-weight:bold;padding:0;position:absolute;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;pointer-events:none;white-space:nowrap;z-index:-1; box-shadow:0 0 0 rgba(0,0,0,0);}
  };
  //添加鼠标移上后的提示信息
  mker.bindTooltip(tiptitle, tipOptin).openTooltip();

  //添加鼠标点击事件

  return mker;
}

export function ShowHideBusLayer(e) {
  let bustype = e.bustype;
  let showhide = e.show;
  let type = "";
  if (bustype == "CctvSite") {
    type = "CctvSite";
  } else if (bustype == BUSTYPE_VTS_CENTER) {
    type = BUSTYPE_VTS_CENTER;
  } else if (bustype == BUSTYPE_VTS_RADAR) {
    type = BUSTYPE_VTS_RADAR;
  } else if (bustype == "SosOrganization") {
    type = BUSTYPE_SOS_ORG;
  } else if (bustype == BUSTYPE_SOS_FLYDEV) {
    type = BUSTYPE_SOS_FLYDEV;
  } else if (bustype == BYSTYPE_EM_WAREHOUSE) {
    type = BYSTYPE_EM_WAREHOUSE;
  }else if (bustype == BYSTYPE_SYS_USER) {
    type = BYSTYPE_SYS_USER;
  }else if (bustype == BYSTYPE_EMMERSHIP) {
    type = BYSTYPE_EMMERSHIP;
  }else if (bustype == BYSTYPE_SOSSHIPPRO) {
    type = BYSTYPE_SOSSHIPPRO;
  }else if (bustype == BYSTYPE_SOSSHIPSOC) {
    type = BYSTYPE_SOSSHIPSOC;
  }else if (bustype == BYSTYPE_ZFCT) {
    type = BYSTYPE_ZFCT;
  }
  if (showhide) {
    showBzx(type);
  } else {
    clearBzx(type);
  }
}
function showBzx(type) {
  clearBzx(type);
  let service, objArray, icon
  if (type === BUSTYPE_CCTV) {
    service = cctvSiteService
    objArray = mapGrouplayerCctvSite
    icon = ICON_CCTV_SITE
  } else if (type === BUSTYPE_VTS_CENTER) {
    service = vtsSubCenterService
    objArray = mapGrouplayerVtsSubCenter
    icon = ICON_VTS_SUB_CENTER
  } else if (type === BUSTYPE_VTS_RADAR) {
    service = vtsRadarStService
    objArray = mapGrouplayerVtsRadarSt
    icon = ICON_VTS_RADAR_ST
  } else if (type === BUSTYPE_SOS_ORG) {
    service = sosOrgService
    objArray = mapGrouplayerSosOrganization
    icon = ICON_SOS_ORG
  } else if (type === BUSTYPE_SOS_FLYDEV) {
    service = sosFlyDeviceService
    objArray = mapGrouplayerSosFlyDevice
    icon = ICON_SOS_FLY_DEV
  } else if (type === BYSTYPE_EM_WAREHOUSE) {
    service = emWarehouseService;
    objArray = mapGrouplayerEmWarehouse;
    icon = ICON_EM_WAREHOUSE;
  } else if (type === BYSTYPE_SYS_USER) {
    service = lawPeopleService;
    objArray = mapGrouplayerSysUser;
    icon = ICON_SYS_USER;
  } else if (type === BYSTYPE_EMMERSHIP) {
    service = emmerShipService;
    objArray = mapGrouplayerEmmerShip;
    icon = ICON_EMMERSHIP;
  } else if (type === BYSTYPE_SOSSHIPPRO) {
    service = sosShipProService;
    objArray = mapGrouplayerSosShipPro;
    icon = ICON_SOSSHIPPRO;
  } else if (type === BYSTYPE_SOSSHIPSOC) {
    service = sosShipSocService;
    objArray = mapGrouplayerSosShipPro;
    icon = ICON_SOSSHIPSOC;
  } else if (type === BYSTYPE_ZFCT) {
    //service = sosShipSocService; //临时先写成固定数据
    objArray = mapGrouplayerZfct;
    icon = ICON_ZFCT;
  }

  let guaranteeSosorgid=sessionStorage.getItem('guaranteeSosorgid'); //搜救机构下拉框中选择的搜救机构id
  let guaranteeSosorgidTreeSelect=sessionStorage.getItem('guaranteeSosorgidTreeSelect'); //弹出搜救机构后选择的搜救结构目录树上的节点
  if (guaranteeSosorgid==null){
    guaranteeSosorgid='';
  }
  if (guaranteeSosorgidTreeSelect==null){
    guaranteeSosorgidTreeSelect='';
  }
  //alert(guaranteeSosorgid+","+guaranteeSosorgidTreeSelect);
  if (type === BYSTYPE_ZFCT) {
    let ary=[];
    let onezzct={};
    onezzct.latitude=38.385555;
    onezzct.longitude=120.92167;
    onezzct.name='执法船艇';
    ary.push(onezzct);
    onezzct={};
    onezzct.latitude=38.153057;
    onezzct.longitude=120.74778;
    onezzct.name='执法船艇';
    ary.push(onezzct);
    showMapObj(ary,mapobj,icon,objArray);
    return;
  }
  service.searchAll().then(ary => {
//    for (let kkk = 0; kkk < ary.length; kkk++) {
//      console.log(ary[kkk]); //为了调试临时先输出数据
//    }
    if (type === BYSTYPE_EMMERSHIP || type === BYSTYPE_SOSSHIPPRO || type === BYSTYPE_SOSSHIPSOC) {
      let querymmsi=getMmsiQuery(ary);
      if (querymmsi!=""){
        shipService.findLocationAll(querymmsi).then(arylocaltion => {
          for (let kkk = 0; kkk < arylocaltion.length; kkk++) {
            console.log(arylocaltion[kkk].terminalCode+","+arylocaltion[kkk].latitude+","+arylocaltion[kkk].longitude);//为了调试临时先输出数据
          }
            for (let m=0;m<arylocaltion.length;m++){
              for (let n=0;n<ary.length;n++){
                if (ary[n].mmsi==arylocaltion[m].terminalCode){
                  ary[n].latitude=arylocaltion[m].latitude;
                  ary[n].longitude=arylocaltion[m].longitude;
                  break;
                }
              }
            }
//          for (let kk = 0; kk < ary.length; kk++) {
//            console.log(ary[kk].mmsi + "," + ary[kk].latitude + "," + ary[kk].longitude); //为了调试临时先输出数据
//          }
          showMapObj(ary,mapobj,icon,objArray);
        });
      }else{
        console.log("ret ship not mmsi");
      }
    } else{
      for (let kk = 0; kk < ary.length; kk++) {
        console.log(ary[kk].latitude + "," + ary[kk].longitude); //为了调试临时先输出数据
      }
      showMapObj(ary,mapobj,icon,objArray);
    }
  })
}

//清除业务对象地图点位
export function clearBzx(type) {
  if (type == BUSTYPE_CCTV) {
    for (var i = 0; i < mapGrouplayerCctvSite.length; i++) {
      var onemarker = mapGrouplayerCctvSite[i];
      mapobj.removeLayer(onemarker);
    }
    mapGrouplayerCctvSite = [];
  } else if (type == BUSTYPE_VTS_CENTER) {
    for (var i = 0; i < mapGrouplayerVtsSubCenter.length; i++) {
      var onemarker = mapGrouplayerVtsSubCenter[i];
      mapobj.removeLayer(onemarker);
    }
    mapGrouplayerVtsSubCenter = [];
  } else if (type == BUSTYPE_VTS_RADAR) {
    for (var i = 0; i < mapGrouplayerVtsRadarSt.length; i++) {
      var onemarker = mapGrouplayerVtsRadarSt[i];
      mapobj.removeLayer(onemarker);
    }
    mapGrouplayerVtsRadarSt = [];
  } else if (type == BUSTYPE_SOS_ORG) {
    for (var i = 0; i < mapGrouplayerSosOrganization.length; i++) {
      var onemarker = mapGrouplayerSosOrganization[i];
      mapobj.removeLayer(onemarker);
    }
    mapGrouplayerSosOrganization = [];
  } else if (type == BUSTYPE_SOS_FLYDEV) {
    for (var i = 0; i < mapGrouplayerSosFlyDevice.length; i++) {
      var onemarker = mapGrouplayerSosFlyDevice[i];
      mapobj.removeLayer(onemarker);
    }
    mapGrouplayerSosFlyDevice = [];
  } else if (type == BYSTYPE_EM_WAREHOUSE) {
    for (var i = 0; i < mapGrouplayerEmWarehouse.length; i++) {
      var onemarker = mapGrouplayerEmWarehouse[i];
      mapobj.removeLayer(onemarker);
    }
    mapGrouplayerEmWarehouse = [];
  } else if (type == BYSTYPE_SYS_USER) {
    for (var i = 0; i < mapGrouplayerSysUser.length; i++) {
      var onemarker = mapGrouplayerSysUser[i];
      mapobj.removeLayer(onemarker);
    }
    mapGrouplayerSysUser = [];
  } else if (type == BYSTYPE_EMMERSHIP) {
    for (var i = 0; i < mapGrouplayerEmmerShip.length; i++) {
      var onemarker = mapGrouplayerEmmerShip[i];
      mapobj.removeLayer(onemarker);
    }
    mapGrouplayerEmmerShip = [];
  } else if (type == BYSTYPE_SOSSHIPPRO) {
    for (var i = 0; i < mapGrouplayerSosShipPro.length; i++) {
      var onemarker = mapGrouplayerSosShipPro[i];
      mapobj.removeLayer(onemarker);
    }
    mapGrouplayerSosShipPro = [];
  } else if (type == BYSTYPE_SOSSHIPSOC) {
    for (var i = 0; i < mapGrouplayerSosShipSoc.length; i++) {
      var onemarker = mapGrouplayerSosShipSoc[i];
      mapobj.removeLayer(onemarker);
    }
    mapGrouplayerSosShipSoc = [];
  } else if (type == BYSTYPE_ZFCT) {
    for (var i = 0; i < mapGrouplayerZfct.length; i++) {
      var onemarker = mapGrouplayerZfct[i];
      mapobj.removeLayer(onemarker);
    }
    mapGrouplayerZfct = [];
  }

}
